﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ConsoleApp.Middleware;

public class ApiAuthorizeAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.Items["User"];
        if (HasAllowAnonymous(context) == false && user == null)
        {
            context.Result = new JsonResult(new { msg = "你无权做这些", code = 401 })
                { StatusCode = StatusCodes.Status401Unauthorized };
        }
    }

    private static bool HasAllowAnonymous(AuthorizationFilterContext context)
    {
        var filters = context.Filters;
        if (filters.OfType<IAllowAnonymousFilter>().Any())
        {
            return true;
        }
        var endpoint = context.HttpContext.GetEndpoint();
        return endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null;
    }
}